package com.jsy.mini12306.ticketsales.controller;

import com.jsy.mini12306.ticketsales.exception.TicketSaleCoreException;
import com.jsy.mini12306.ticketsales.service.TicketService;
import com.jsy.mini12306.ticketsales.service.TrainCalendarService;
import com.jsy.mini12306.ticketsales.vo.BuyTicketResCode;
import com.jsy.mini12306.ticketsales.vo.TicketOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/9/8
 */

@Slf4j
@RestController
@RequestMapping("ticket")
public class BuyTicketController {

    @Resource
    TicketService ticketService;

    @Resource
    TrainCalendarService trainCalendarService;

    @PostMapping("/order")
    public ResponseEntity<BuyTicketResCode> buyTickets(@RequestBody TicketOrderVO ticketOrder) {
        if (!trainCalendarService.isWorking(ticketOrder.getTrain().getTrainId(),ticketOrder.getDepartDate())) {
            return ResponseEntity.ok(BuyTicketResCode.NONE);
        }
        try {
            boolean succ = ticketService.processTicketOrder(ticketOrder);
            if (succ) return ResponseEntity.ok(BuyTicketResCode.OK);
            else return ResponseEntity.ok(BuyTicketResCode.FAIL);
        } catch (TicketSaleCoreException e) {
            return ResponseEntity.internalServerError().body(BuyTicketResCode.ERROR);
        }
    }


}
